package com.ht.guice.jooq;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.matcher.Matchers;
import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;

import javax.sql.DataSource;

/**
 * Created by bcw on 14-4-3.
 */
public class JooqPersistModule extends AbstractModule {

    private Configuration configuration;
    private TxDataSourceConnectionProvider connectionProvider;
    private DataSource dataSource;
    private SQLDialect dialect;

    public JooqPersistModule(DataSource dataSource, SQLDialect dialect) {
        this.dataSource = dataSource;
        this.dialect = dialect;
    }

    @Override
    protected void configure() {

//        DataSourceConnectionProvider connectionProvider = new DataSourceConnectionProvider(dataSource);

        connectionProvider = new TxDataSourceConnectionProvider(dataSource);
        bind(TxDataSourceConnectionProvider.class).toInstance(connectionProvider);

        configuration = new DefaultConfiguration().set(connectionProvider).set(dialect);
        bind(Configuration.class).toInstance(configuration);// bind configuration

        // 事务拦截
        TransactionalMethodInterceptor transactionInterceptor = new TransactionalMethodInterceptor();
        requestInjection(transactionInterceptor);
        bindInterceptor(Matchers.annotatedWith(Transactional.class), Matchers.any(), transactionInterceptor);
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(Transactional.class), transactionInterceptor);


        // DAO依赖注入
/*        try {
            bind(AuthorDao.class).toConstructor(AuthorDao.class.getConstructor(Configuration.class)).asEagerSingleton();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }*/
    }

    @Provides
    DSLContext provideDSLContext() {
        return DSL.using(configuration);
    }

}
